<template>
  <div>
    <!-- <el-row>
      <el-col :span="6">
        <el-form-item label="病患姓名">
          <el-input
            v-model="search.name"
            placeholder="请输入病患姓名"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="6" :offset="2">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
      </el-col>
    </el-row> -->
    <el-row>
      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="name"
            label="病患姓名"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="phone"
            label="病患手机号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="familyMembers[0].familyPhone"
            label="家属手机号"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <p v-if="scope.row.familyMembers.length == 0">暂无绑定家属</p>
              <p v-else>{{ scope.row.familyMembers[0]?.familyPhone }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="deviceNo"
            label="设备号"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <p v-if="scope.row.deviceNo != ''">{{ scope.row.deviceNo }}</p>
              <p v-if="scope.row.deviceNo == null">暂无绑定手环</p>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" align="center" width="auto">
            <template #default="scope">
              <el-button
                v-if="scope.row.isDeviceBound"
                style="color: red"
                link
                type="primary"
                size="small"
                @click="del_bound(scope.row)"
                >解绑手环</el-button
              >
              <el-button
                v-else
                link
                type="primary"
                size="small"
                style="color: rgb(6, 187, 6)"
                @click="
                  bound(scope.row);
                  dialogVisible = true;
                "
                >绑定手环</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        v-model="dialogVisible"
        title="绑定手环"
        width="50%"
        :before-close="handleClose"
      >
        <el-row>
          <el-col>
            <!-- <el-input
              v-model="deviceNo"
              placeholder="请输入绑定手环号"
              clearable
            /> -->
            <el-select
              v-model="deviceNo"
              filterable
              remote
              :remote-method="debouncedRemoteFilter"
              placeholder="请输入绑定手环号"
            >
              <el-option
                v-for="item in filteredOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col>
            <el-button
              style="float: right; margin: 20px"
              link
              type="primary"
              @click="bound_bt()"
              >绑定</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import {
  GetAllUsersByPaging,
  BindingBracelet,
  UnbindBracelet,
  GetUnboundDeviceNos,
} from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";
defineOptions({
  name: "Binghuanxinxi",
});

const Data = ref([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const dialogVisible = ref(false);

const add = () => {
  dialogVisible.value = true;
};

// 分页查询
const GetList = () => {
  Data.value = [];
  const data = ref({
    token: getToken().accessToken,
    body: {
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
    },
  });
  GetAllUsersByPaging(data.value)
    .then((res: any) => {
      console.log("查询所有用户返回", res);
      if (res.code == 200) {
        Data.value.push(...res.data.users);
        Total.value = res.data.totalRecords;
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
};

//查询手环号
const Get_Shouhuan = () => {
  const data = ref({
    token: getToken().accessToken,
    body: {},
  });
  GetUnboundDeviceNos(data.value).then((res: any) => {
    console.log("全部手环号", res);
    res.data.forEach((item) => {
      options.value.push({
        label: item,
        value: item,
      });
    });
  });
};
//绑定手环
const now_user = ref<any>("");
const deviceNo = ref<any>("");
const bound = (row) => {
  deviceNo.value = "";
  now_user.value = row.id;
  Get_Shouhuan();
};



const options = ref<any>([]);

const filteredOptions = ref<any[]>(options.value);

// 手写防抖函数
function debounce(func: Function, wait: number) {
  let timeout: ReturnType<typeof setTimeout>;
  return function (...args: any[]) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

// 自定义远程过滤方法
const remoteFilter = (query: string) => {
  if (!query) {
    filteredOptions.value = options.value;
    return;
  }
  const lowerCaseQuery = query.toLowerCase();
  filteredOptions.value = options.value.filter((item) =>
    item.label.toLowerCase().includes(lowerCaseQuery)
  );
};
// 创建防抖版本的过滤函数
const debouncedRemoteFilter = debounce(remoteFilter, 300);
const bound_bt = () => {
  const data = ref({
    token: getToken().accessToken,
    body: {
      deviceNo: deviceNo.value,
      userid: now_user.value,
    },
  });
  BindingBracelet(data.value)
    .then((res: any) => {
      console.log("绑定手环返回", res);
      if (res.code == 200) {
        GetList();
        message("绑定完成", { type: "success" });
        dialogVisible.value = false;
      } else if (res.code == 405) {
        message(res.message, { type: "error" });
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
};

//解绑手环
const del_bound = (row) => {
  now_user.value = row.id;
  deviceNo.value = row.deviceNo;
  ElMessageBox.confirm("确认解绑?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const data = ref({
        token: getToken().accessToken,
        body: {
          deviceNo: deviceNo.value,
          userid: now_user.value,
        },
      });
      UnbindBracelet(data.value)
        .then((res: any) => {
          console.log("解除绑定返回", res);
          if (res.code == 200) {
            GetList();
            ElMessage({
              type: "success",
              message: "解除绑定成功",
            });
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};

// 监听页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleClose = (done: () => void) => {
  deviceNo.value = "";
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped></style>
